package com.itda.aop;

import com.alibaba.fastjson.JSONObject;
import com.itda.mapper.OperateLogMapper;
import com.itda.pojo.OperateLog;
import com.itda.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Author: itda
 * @Date: 2024/5/3 14:11
 * @Description: LogAspect
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itda.annotation.Log)")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        //操作人的id
        //获取请求头中的jwt令牌,解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operaterUser = (Integer) claims.get("id");

        //操作时间
        LocalDateTime operaterTime = LocalDateTime.now();

        //操作类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = proceedingJoinPoint.getSignature().getName();

        //操作方法参数
        Object[] args = proceedingJoinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        //原始方法开始时间
        long begin = System.currentTimeMillis();
        //方法返回值
        Object result = proceedingJoinPoint.proceed();
        //原始方法结束时间
        long end = System.currentTimeMillis();
        String returnValue = JSONObject.toJSONString(result);
        //操作耗时
        Long costTime = end - begin;


        OperateLog operateLog = new OperateLog(null,operaterUser,operaterTime,className,methodName,methodParams,returnValue,costTime);


        operateLogMapper.insert(operateLog);

        log.info("AOP记录日志:{}",operateLog);

        return result;
    }
}
